package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatFangXinQianBaoApply;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeFangXinQianBao;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 安心分期出-放鑫钱包全流程28
 *
 * @author 李源聪
 */
@ApiPlan(productId = "362", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatFangXinQianBaoPhontMaskConvert implements ApiPlatformPhoneMd5ConvertHandler {

    private static final String KEY = "a2c7b988rt1ffbf8";
    private static final String IV = "1381234567865874";
    private static final String CHANNEL_CODE = "4FAPeXiIwK";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        //  撞库流程
        ApiPlatDataExchangeFangXinQianBao apiPlatDataExchange = new ApiPlatDataExchangeFangXinQianBao();
        // 拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        // 手机号md5
        apiPlatDataExchange.setPhone(apiDataExchangeParameter.getPhoneMd5());
        // 用户名
        apiPlatDataExchange.setUserName("浩安星");
        // 城市
        apiPlatDataExchange.setCity(apiDataExchangeParameter.getCity());
        // ip
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getIp())) {
            apiPlatDataExchange.setIp(apiDataExchangeParameter.getIp());
        } else {
            apiPlatDataExchange.setIp("127.0.0.1");
        }
        // 年龄
        apiPlatDataExchange.setAge(apiDataExchangeParameter.getAge());
        // 性别
        String sex = ChooseEq.create(apiDataExchangeParameter.getSex())
                .when("0", "1")
                .when("1", "0")
                .end();
        apiPlatDataExchange.setSex(sex);
        // 贷款金额
        apiPlatDataExchange.setLoanAmount(apiFieldConverter.getLoanAmountUnit());
        // 贷款期限
        String value = ChooseEq.create(apiDataExchangeParameter.getLoanTerm())
                .when("1", "3")
                .when("2", "6")
                .when("3", "12")
                .when("4", "24")
                .when("5", "36")
                .when("6", "60")
                .end("3");
        apiPlatDataExchange.setLoamTerm(value);
        // 职业(200:上班族,300:自由职业,400:企业主,500:个体户,800:公务员,900:其他),默认传200;
        String career = ChooseEq.create(apiDataExchangeParameter.getCareer())
                .when("1", "200")
                .when("2", "300")
                .when("3", "400")
                .when("4", "900")
                .when("5", "500")
                .end();
        apiPlatDataExchange.setProfession(career);
        // 月收入
        apiPlatDataExchange.setIncomeMonth(String.valueOf(apiFieldConverter.getMonthlySalaryNumber()));
        // 工资发放形式 1.银行代发打卡 2.现金收入 3.自存
        String salaryPayMethod = ChooseEq.create(apiDataExchangeParameter.getSalaryPayMethod())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .end("10");
        apiPlatDataExchange.setPayoffType(salaryPayMethod);
        // 单位工龄 10:0-6个月，20:6~12个月，30:12个月以上
        String yearsService = ChooseEq.create(apiDataExchangeParameter.getYearsService())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .end("10");
        apiPlatDataExchange.setWorkingYears(yearsService);
        // 公积金 10.无公积金 20.缴纳6个月以下 0.缴纳6个月以上 40.有公积金
        String providentFund = ChooseEq.create(apiDataExchangeParameter.getProvidentFund())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end();
        apiPlatDataExchange.setGjjScop(providentFund);
        // 社保缴纳 10.无社保 20.缴纳6个月以下 30.缴纳6个月以上 40.有社保
        String socialSecurity = ChooseEq.create(apiDataExchangeParameter.getSocialSecurity())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end();
        apiPlatDataExchange.setSbScop(socialSecurity);
        // 房产情况(0:无房产,10:有房产，不抵押,20:有房产，可抵押)
        String realEstateInfo = ChooseEq.create(apiDataExchangeParameter.getRealEstateInfo())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "20")
                .when("5", "10")
                .when("6", "20")
                .end();
        apiPlatDataExchange.setHouse(realEstateInfo);
        // 车产情况(0:无车产,10:有车产，不抵押,20:有车产，可抵押)
        String carInfo = ChooseEq.create(apiDataExchangeParameter.getCarInfo())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end();
        apiPlatDataExchange.setCar(carInfo);
        // 保单情况(0:无保险保单,10:缴纳未满1年,20:缴纳1年以上)
        String insurancePolicy = ChooseEq.create(apiDataExchangeParameter.getInsurancePolicy())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end();
        apiPlatDataExchange.setBaodanScop(insurancePolicy);
        // 芝麻分(0:无芝麻分,10:600分以下,20:600~650分,30:650~700分,40:700分以上)
        String sesameCredit = ChooseEq.create(apiDataExchangeParameter.getSesameCredit())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .when("4", "40")
                .end();
        apiPlatDataExchange.setSesameScore(sesameCredit);
        // 信用卡额度
        String creditLimit = ChooseEq.create(apiDataExchangeParameter.getCreditLimit())
                .when("1", "0")
                .when("2", "10")
                .when("3", "10")
                .when("4", "10")
                .when("5", "10")
                .when("6", "10")
                .end();
        apiPlatDataExchange.setCreditCard(creditLimit);
        //  加密方法
        AES aes = AES.createCbc(KEY.getBytes(), IV.getBytes());
        String json = JsonUtils.toJson(apiPlatDataExchange);
        String encrypt = aes.encryptToBase64Str(json);
        Map<Object, Object> dataMap = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("data", encrypt);
        });
        return JsonUtils.toJson(dataMap);
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 10000)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        JSONObject resData = jsonObject.getJSONObject("data");
        if (resData == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONObject product = resData.getJSONObject("product");

        BigDecimal price = resData.getBigDecimal("settleAmount");
        String productName = product.getString("prodName");
        String logo = product.getString("prodLogo");
        List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
            //  获取协议
            JSONArray listProtocolResult = resData.getJSONArray("protocolList");
            IteratorUtils.array(listProtocolResult, (protocolResult, index) -> {
                JSONObject protocolObject = listProtocolResult.getJSONObject(index);
                ApiProtocol protocol = new ApiProtocol();
                protocol.setProtocolName(protocolObject.getString("protoName"));
                protocol.setProtocolUrl(protocolObject.getString("protoUrl"));
                newList.add(protocol);
            });
        });

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();
        result.setPrice(price);
        result.setLogoPath(logo);
        result.setDisplayName("放鑫钱包");
        result.setProductName(productName);
        result.setProtocolList(protocolList);
        return result;
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        //  撞库流程
        ApiPlatFangXinQianBaoApply apiPlatDataExchange = new ApiPlatFangXinQianBaoApply();
        // 拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        // 手机号md5
        apiPlatDataExchange.setPhone(apiApplyParameter.getPhone());
        // 用户名
        apiPlatDataExchange.setUserName(apiApplyParameter.getUserName());
        // 城市
        apiPlatDataExchange.setCity(apiApplyParameter.getCity());
        // ip
        if (ValidParam.isNotEmpty(apiApplyParameter.getIp())) {
            apiPlatDataExchange.setIp(apiApplyParameter.getIp());
        } else {
            apiPlatDataExchange.setIp("127.0.0.1");
        }
        // 年龄
        apiPlatDataExchange.setAge(apiApplyParameter.getAge());
        // 性别
        String sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", "1")
                .when("1", "0")
                .end();
        apiPlatDataExchange.setSex(sex);
        // 贷款金额
        apiPlatDataExchange.setLoanAmount(apiFieldConverter.getLoanAmountUnit());
        // 贷款期限
        String value = ChooseEq.create(apiApplyParameter.getLoanTerm())
                .when("1", "3")
                .when("2", "6")
                .when("3", "12")
                .when("4", "24")
                .when("5", "36")
                .when("6", "60")
                .end("3");
        apiPlatDataExchange.setLoamTerm(value);
        // 职业(200:上班族,300:自由职业,400:企业主,500:个体户,800:公务员,900:其他),默认传200;
        String career = ChooseEq.create(apiApplyParameter.getCareer())
                .when("1", "200")
                .when("2", "300")
                .when("3", "400")
                .when("4", "900")
                .when("5", "500")
                .end();
        apiPlatDataExchange.setProfession(career);

        // 月收入
        apiPlatDataExchange.setIncomeMonth(String.valueOf(apiFieldConverter.getMonthlySalaryNumber()));
        // 工资发放形式 1.银行代发打卡 2.现金收入 3.自存
        String salaryPayMethod = ChooseEq.create(apiApplyParameter.getSalaryPayMethod())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .end("10");
        apiPlatDataExchange.setPayoffType(salaryPayMethod);
        // 单位工龄 10:0-6个月，20:6~12个月，30:12个月以上
        String yearsService = ChooseEq.create(apiApplyParameter.getYearsService())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .end("10");
        apiPlatDataExchange.setWorkingYears(yearsService);
        // 公积金 10.无公积金 20.缴纳6个月以下 0.缴纳6个月以上 40.有公积金
        String providentFund = ChooseEq.create(apiApplyParameter.getProvidentFund())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end();
        apiPlatDataExchange.setGjjScop(providentFund);
        // 社保缴纳 10.无社保 20.缴纳6个月以下 30.缴纳6个月以上 40.有社保
        String socialSecurity = ChooseEq.create(apiApplyParameter.getSocialSecurity())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end();
        apiPlatDataExchange.setSbScop(socialSecurity);
        // 房产情况(0:无房产,10:有房产，不抵押,20:有房产，可抵押)
        String realEstateInfo = ChooseEq.create(apiApplyParameter.getRealEstateInfo())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "20")
                .when("5", "10")
                .when("6", "20")
                .end();
        apiPlatDataExchange.setHouse(realEstateInfo);
        // 车产情况(0:无车产,10:有车产，不抵押,20:有车产，可抵押)
        String carInfo = ChooseEq.create(apiApplyParameter.getCarInfo())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end();
        apiPlatDataExchange.setCar(carInfo);
        // 保单情况(0:无保险保单,10:缴纳未满1年,20:缴纳1年以上)
        String insurancePolicy = ChooseEq.create(apiApplyParameter.getInsurancePolicy())
                .when("1", "0")
                .when("2", "10")
                .when("3", "20")
                .when("4", "10")
                .end();
        apiPlatDataExchange.setBaodanScop(insurancePolicy);
        // 芝麻分(0:无芝麻分,10:600分以下,20:600~650分,30:650~700分,40:700分以上)
        String sesameCredit = ChooseEq.create(apiApplyParameter.getSesameCredit())
                .when("1", "10")
                .when("2", "20")
                .when("3", "30")
                .when("4", "40")
                .end();
        apiPlatDataExchange.setSesameScore(sesameCredit);
        // 信用卡额度
        // 信用卡额度
        String creditLimit = ChooseEq.create(apiApplyParameter.getCreditLimit())
                .when("1", "0")
                .when("2", "10")
                .when("3", "10")
                .when("4", "10")
                .when("5", "10")
                .when("6", "10")
                .end();
        apiPlatDataExchange.setCreditCard(creditLimit);
        //  加密方法
        AES aes = AES.createCbc(KEY.getBytes(), IV.getBytes());
        String json = JsonUtils.toJson(apiPlatDataExchange);
        String encrypt = aes.encryptToBase64Str(json);
        Map<Object, Object> dataMap = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("data", encrypt);
        });
        return JsonUtils.toJson(dataMap);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 10000)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}
